﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WareHouse.App
{
    using System.Drawing.Printing;

    using DevExpress.XtraGrid;
    using DevExpress.XtraPrinting;

    using WareHouse.Contract.Models;
    using WareHouse.Contract.Services;
    using WareHouse.Service.Services;

    public partial class FrmOrderHistory : Form
    {
       private IWareHouseService wareHouseService;

        private List<OrderDetailModel> listOrderDetailModels;
        private List<OrderModel> listOrderModels;
        public FrmOrderHistory()
        {
            listOrderDetailModels = new List<OrderDetailModel>();
            wareHouseService = new WareHouseService();
            listOrderModels = new List<OrderModel>();

            InitializeComponent();
          
        }

       
        private void FrmOrderHistory_Load(object sender, EventArgs e)
        {
            CheckRole();
            CleanLabel();
            LoadAllOrder();
        }
        private void CheckRole()
        {
            if (!wareHouseService.R(General.groupUserId, "orderhistory_updatestatus"))
            {
                btnUpdateState.Enabled = false;

            }
            if (!wareHouseService.R(General.groupUserId, "orderhistory_printagain"))
            {
                btnPrintAgain.Enabled = false;

            }


        }

        private void LoadAllOrder()
        {
            wareHouseService=new WareHouseService();
            var listOrder = wareHouseService.ListAllOrder();
            gridListHd.DataSource = listOrder.ToArray();
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                CleanLabel();
                var modelOrder = (OrderModel)gridView1.GetRow(gridView1.GetSelectedRows()[0]);
                if (modelOrder != null)
                {
                    lblCustomerName.Text = modelOrder.CompanyName;
                    lblCustomerId.Text = modelOrder.CompanyId.ToString();
                    lblEmployerName.Text = modelOrder.EmployerName;
                    lblDate.Text = string.Format("{0:dd/MM/yyyy}", modelOrder.DateCreate);
                    chkIsFinish.Checked = modelOrder.IsFinish;
                    lblExportId.Text = modelOrder.OrderId;
                    LoadDetailOrderByOrderId(modelOrder.OrderId);
                    
                   
                    btnPrintAgain.Enabled = true;
                    btnUpdateState.Enabled = true;
                    return;
                }
                btnPrintAgain.Enabled = false;
                btnUpdateState.Enabled = false;
            }
            catch (Exception)
            {


            }
        }
        private void ReCanculateSTT()
        {
            for (int i = 0; i < gridView2.RowCount; i++)
            {
                gridView2.SetRowCellValue(i, "Stt", i + 1);
            }

        }

        private void LoadDetailOrderByOrderId(string orderId)
        {
            var listDetailOrder = wareHouseService.ListItemByOrderId(orderId);
            gridItems.DataSource = listDetailOrder.ToArray();
            ReCanculateSTT();
        }

        private void btnUpdateState_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn cập nhật lại tình trạng thực của đơn hàng này ?","Thông báo",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
            {
                try
                {
                    var modelOrder = (OrderModel)gridView1.GetRow(gridView1.GetSelectedRows()[0]);
                    if (modelOrder != null)
                    {
                        modelOrder.IsFinish = chkIsFinish.Checked;
                        if(wareHouseService.UpdateStatusFinishOrnotForOrder(modelOrder))
                        {
                            MessageBox.Show("Đã cập nhật thành công");
                            this.LoadAllOrder();
                        }

                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Có lỗi trong quá trình cập nhật. Vui lòng thử lại sau");

                }
            }
        }


        private void printLink_CreateReportHeaderArea(object sender, DevExpress.XtraPrinting.CreateAreaEventArgs e)
        {

            DevExpress.XtraPrinting.TextBrick brick;

            brick = e.Graph.DrawString("ĐƠN ĐẶT HÀNG"+ Environment.NewLine +"( "+lblDate.Text+")", Color.Black, new RectangleF(0, 0, 725, 80), DevExpress.XtraPrinting.BorderSide.None);

            brick.Font = new Font("Tahoma", 22);

            brick.StringFormat = new DevExpress.XtraPrinting.BrickStringFormat(StringAlignment.Center);

        }
        private void PrintListItemInGrid(GridControl gridControl)
        {
            PrintableComponentLink printLink = new PrintableComponentLink();
            printLink.CreateReportHeaderArea += this.printLink_CreateReportHeaderArea;

            PrintingSystem printingSystem = new PrintingSystem();
            printingSystem.Links.AddRange(new object[] { printLink });
            printLink.PaperKind = PaperKind.A4;
            printLink.Component = gridControl;

            printLink.Images.Add(Properties.Resources.Logo);

            printLink.Margins.Top = 200;
            printLink.Margins.Left = 25;
            printLink.Margins.Right = 25;


            var agencyName = "";
            var agencyAddress = "";
            var agencyPhone = "";
            var companyName = "";
            var companyAddress = "";
            var companyPhone = "";

            if (lblCustomerId.Text != "")
            {
                var company = wareHouseService.GetcompanyBycompanyId(int.Parse(lblCustomerId.Text));
                if (company != null)
                {
                    companyAddress = company.CompanyAddress;
                    companyName = company.CompanyName;
                    companyPhone = company.Phone;
                }
                if (company == null)
                {
                    MessageBox.Show("Hiện tại chưa có khách hàng được chọn");
                    return;
                }

            }
            var currentAgency = wareHouseService.GetCurrentAgency();
            if (currentAgency == null)
            {
                MessageBox.Show("Hiện tại chưa có đại lý nào được chọn");
                return;
            }

            agencyAddress = currentAgency.AgencyAddress;
            agencyName = currentAgency.AgencyName;
            agencyPhone = currentAgency.Phone;
            #region Define content of header
            PageHeaderArea pgHArea = new PageHeaderArea();

            pgHArea.Font = new Font(new FontFamily("Tahoma"), 12, FontStyle.Regular);

            pgHArea.Content.AddRange(
                new string[]
                    {
                        "Đại lý : "+ agencyName+ Environment.NewLine 
                        + "Địa chỉ : "+agencyAddress + Environment.NewLine
                        + "Điện thoại : "+agencyPhone + Environment.NewLine + "  " + Environment.NewLine
                        + "Công ty : "+companyName + Environment.NewLine 
                        + "Địa chỉ : "+companyAddress
                        + Environment.NewLine + "Điện Thoại : "+companyPhone + Environment.NewLine + "" + Environment.NewLine + ""
                        + Environment.NewLine, Environment.NewLine + Environment.NewLine + "", "[Image 0]"
                    });

            #endregion
            #region Define content of footer
            PageFooterArea pgFArea = new PageFooterArea();

            pgFArea.Font = new Font(new FontFamily("Tahoma"), 10, FontStyle.Bold);

            decimal totalSummary = 0;
            var summaryValue = this.gridView2.Columns["Total"].SummaryItem.SummaryValue;
            if (summaryValue != null && decimal.TryParse(summaryValue.ToString(), out totalSummary))
            {
                pgFArea.Content.AddRange(
                new string[]
                    {"","",
                        "Thành tiền : "+ String.Format("{0:N0}",totalSummary)+" VND"+Environment.NewLine
                    +"Bằng chữ :"+ General.DetachMoney((double)totalSummary)
                      
                  
                    });

            }
            
            #endregion

            // Create a PageHeaderFooter object for this link.
            printingSystem.Links[0].PageHeaderFooter = new PageHeaderFooter(pgHArea, pgFArea);


            printLink.ShowPreview();
        }

        private void btnPrintAgain_Click(object sender, EventArgs e)
        {
            this.PrintListItemInGrid(gridItems);
        }

        private void gridListHd_Click(object sender, EventArgs e)
        {

        }

        private void CleanLabel()
        {
            lblCustomerId.Text = "";
            lblCustomerName.Text = "";
            lblDate.Text = "";
            lblEmployerName.Text = "";
            lblExportId.Text = "";
        }

    }
}
